package com.thortec.farmsys.utils;


import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @auther ny by:dbw
 * @create 2018-07-18
 */
public class CookieUtils {
    public  static void set(String name,String value,Integer expire,HttpServletResponse response){
        Cookie cookie = new Cookie(name,value);
        cookie.setMaxAge(expire);
        response.addCookie(cookie);
    }

    public static Cookie get(String name, HttpServletRequest request){
        Map<String, Cookie> cookieMap = readCookie2Map(request);
        if(null!=cookieMap){
            return  cookieMap.get(name);
        }
       return null;
    }

    private static Map<String,Cookie> readCookie2Map(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        HashMap<String,Cookie> cookieMap = new HashMap<>();
        if(cookies!=null){
            for(Cookie cookie:cookies){
                cookieMap.put(cookie.getName(),cookie);
            }
            return  cookieMap;
        }
        return  null;
    }
}
